﻿//Author: Christian TQ
//License: MIT License
using Microsoft.SharePoint;
using Microsoft.Office.Server.SocialData;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using System;
using System.Collections.Generic;
using System.Collections;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using TQ.Sharepoint.Webparts;

namespace TQ.Sharepoint.Webparts.Microblogger
{
    public partial class MicrobloggerUserControl : UserControl
    {
        #region "VARIABLES"
        const string CACHE_COLLEAGUE_KEY="ColleagueCache";
        string _cacheLoginNameKey = SPContext.Current.Web.CurrentUser.LoginName;
        private string _mySite;
        private int _numItems;
        private int _numDays;
        public int numItems { get { return _numItems; } set { _numItems = value; } }
        public int numDays { get { return _numDays; } set { _numDays = value; } }
        List<MicrobloggerData> _userNotes = new List<MicrobloggerData>();
        #endregion
        #region "EVENTS"
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                    GetAllComments();
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
              //System.Diagnostics.EventLog.WriteEntry(this.GetType().ToString(), ex.ToString());
            }
        }

      protected void butGetLatest_Click(object sender, EventArgs e)
      {
          try { GetLatestPosts(); }
          catch (Exception ex) { System.Diagnostics.EventLog.WriteEntry(this.GetType().ToString(), ex.ToString()); }
          
      }

  
      protected void butPost_Click(object sender, EventArgs e)
        {
            try
            {
                UserProfile user = MicrobloggerProcess.GetCurrentUserProfile();
                string userURL = user.PersonalUrl.AbsoluteUri.ToString();
                string dot = "%2E";
                string postMsg = MicrobloggerProcess.DecodeHtml(txtPost.Text, this);

                if (!string.IsNullOrEmpty(txtUrlLink.Text))
                    postMsg += txtUrlLink.Text.ToLink();

                if (!string.IsNullOrEmpty(txtImgLink.Text))
                    postMsg += txtImgLink.Text.ToImage();

                if (txtSendto.Text != string.Empty)
                {
                    string colleagueUrl;
                    colleagueUrl = userURL.Replace(user.DisplayName.Replace(".", dot).RemoveDomain(),
                                   txtSendto.Text.Replace(".",dot));

                    using (SPWeb web = SPContext.Current.Site.OpenWeb(colleagueUrl))
                    {
                        SocialCommentManager scm = new SocialCommentManager(SPServiceContext.GetContext(web.Site));
                        scm.AddComment(new Uri(colleagueUrl), postMsg);
                    }
                }
                else
                {
                    using (SPWeb web = SPContext.Current.Site.OpenWeb(userURL))
                    {
                        SocialCommentManager scm = new SocialCommentManager(SPServiceContext.GetContext(web.Site));
                        scm.AddComment(new Uri(userURL), postMsg);
                    }
                }
                

                GetLatestPosts();
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
                //System.Diagnostics.EventLog.WriteEntry(this.GetType().ToString(), ex.ToString());       
            }   
        }
        #endregion
      #region "METHODS"
      private void GetAllComments()
      {

          string html = string.Concat("<TABLE class=ms-socialCommentItem><TBODY><TR>",
              "<TD class=socialcomment-image border=1 vAlign=left rowSpan=2><IMG alt='User Photo' src='{4}'/> </TD>" ,
              "<TD class=socialcomment-IMPawn rowSpan=2 align=left><DIV class=socialcomment-IMPawn><SPAN>",
              "<img class='PresenceImage' src='/_layouts/images/imnhdr.gif' onload=\"IMNRC('{6}')\" name=\"imnmark\" ShowOfflinePawn=\"1\" id=\"contact_im,type=sip\"/>",
              "</SPAN></DIV></TD><TD class=socialcomment-top vAlign=left><SPAN class=socialcomment-username><A class=usercomment href='{0}'>{1}</A>{5}",
              "</SPAN><SPAN class=socialcomment-time>{2}</SPAN></TD></TR><TD class=socialcomment-bottom vAlign=left colSpan=3>",
              "<DIV class=socialcomment-contents>{3}</DIV><div><A href=\"#\" onclick=\"javascript:RePost(this);return false; \" class='mb-Repost'>Re-post</a></div></TD></TR></TBODY></TABLE>");


          if (Cache.Get(_cacheLoginNameKey) == null)
          {
              GetColleagues();
              Cache.Add(_cacheLoginNameKey, _userNotes, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(20),
              CacheItemPriority.Normal, null);
          }
          else
          {
              _userNotes = (List<MicrobloggerData>)Cache.Get(_cacheLoginNameKey);
              RegisterScriptClientStartup((string)Cache.Get(CACHE_COLLEAGUE_KEY));
          }
          _userNotes.Sort((x, y) => DateTime.Compare(y.datePosted, x.datePosted));
          string strNote = string.Empty;
          foreach (MicrobloggerData user in _userNotes)
          {


              if (user.profileOwner == user.noteOwner)
                  strNote = string.Format(html, user.profileURL, user.profileOwner, user.elapsedTime, user.comment, user.profilePic, string.Empty, user.profileEmail);
              else
              {
                  String toUser = string.Format(" to <A href='{0}'>{1}</A>", user.profileURL, user.profileOwner);
                  strNote = string.Format(html, user.noteOwnerURL, user.noteOwner, user.elapsedTime, user.comment, user.noteOwnerPic, toUser, user.profileEmail);
              }

              litNote.Text += strNote;
          }

          
      }

      private void GetColleagues()
        {        

            string profileThumb = string.Empty;
            UserProfile userProfile = MicrobloggerProcess.GetCurrentUserProfile();
            string colleagues=string.Empty;
            _mySite = userProfile.PersonalUrl.ToString().GetMySiteHostUrl();
            string colleagueName;
          
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {   
            using (SPWeb web = SPContext.Current.Site.OpenWeb(_mySite))
            {
                foreach (Colleague colleague in userProfile.Colleagues.GetItems())
                {
                    
                    colleagueName = colleague.Profile.DisplayName.RemoveDomain();
                    profileThumb = MicrobloggerProcess.GetProfilePic(colleague, null);
                    GetSocialComments(web, colleagueName, colleague.Url.ToString(), profileThumb, colleague.Profile.ToWorkEMail());
                    colleagues += "'" + colleagueName + "',";
                }

            
                profileThumb = MicrobloggerProcess.GetProfilePic(null, userProfile);
                GetSocialComments(web, userProfile.DisplayName.RemoveDomain(), userProfile.PersonalUrl.AbsoluteUri.ToString(), profileThumb,userProfile.ToWorkEMail());
               
                
                if(Cache.Get(CACHE_COLLEAGUE_KEY)==null)
                    Cache.Add(CACHE_COLLEAGUE_KEY, colleagues, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(20),
                  CacheItemPriority.Normal, null);
                RegisterScriptClientStartup(colleagues);

            }
         });
        }

  
      private void GetSocialComments(SPWeb web, string profileOwner, string profileURL, string profilePic, string profileEmail)
      {
          
                    SocialCommentManager scm = new SocialCommentManager(SPServiceContext.GetContext(web.Site));
                    SocialComment[] scList = scm.GetComments(new Uri(profileURL),100,0,DateTime.Now.AddDays(numDays.ToNegative()));
                    
                   
                    foreach (SocialComment comment in scList)
                    {
                        _userNotes.Add(new MicrobloggerData(profileOwner, comment.Owner.DisplayName.RemoveDomain(), 
                        comment.Comment, comment.LastModifiedTime, comment.LastModifiedTime.GetElapsedTime(),
                       profileURL, comment.Owner.PersonalUrl.ToString(), profilePic, MicrobloggerProcess.GetProfilePic(null, comment.Owner), profileEmail));
                    }
      }

      private void RegisterScriptClientStartup(string colleagues)
      {
              StringBuilder csScript = new StringBuilder();
              csScript.AppendLine("<script type=\"text/javascript\">");
              csScript.Append("var config = {");
              csScript.Append("pageItems: " + _numItems);
              csScript.AppendLine("};");
              csScript.AppendLine("$(document).ready(function () {");
              csScript.AppendLine("$('#" + txtSendto.ClientID + "').keypress(function (event) {");
              csScript.AppendLine("$(function() {");
              csScript.Append("var colleagues = [");
              csScript.Append(colleagues.TrimEnd(','));
              csScript.AppendLine("];");
              csScript.AppendLine("$('#" + txtSendto.ClientID + "').autocomplete({ source: colleagues });");
              csScript.AppendLine("});");
              csScript.AppendLine("});");
              csScript.AppendLine("});");
              csScript.Append("</script>");
              litScript.Text = csScript.ToString();

      }

      
        private void GetLatestPosts()
        {
            Cache.Remove(_cacheLoginNameKey);
            Cache.Remove(CACHE_COLLEAGUE_KEY);
            litNote.Text = string.Empty;
            GetAllComments();
            txtPost.Text = "What's up?";
            txtSendto.Text = string.Empty;
        }
      #endregion

        
    }//end class
}//end namespace
